package com.our.learning.infrastructure.pojo;

import com.our.learning.infrastructure.constant.ResponseStatusEnum;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : Ice'Clean
 * @date : 2022-01-29
 * <p>
 * 返回给前端的固定格式
 */
public class Response {
    /**
     * 返回的状态码，由 ResponseStatusEnum 给定
     */
    private Integer status;
    /**
     * 附加的信息
     */
    private String msg;
    /**
     * 返回的数据
     */
    private Map<String, Object> data = new HashMap<>();

    public Response(ResponseStatusEnum status) {
        setStatus(status);
    }

    public Response addData(String name, Object value) {
        data.put(name, value);
        return this;
    }

    public Response removeData(String name) {
        data.remove(name);
        return this;
    }

    public boolean isOk() {
        return status == ResponseStatusEnum.OK.value();
    }

    public Integer getStatus() {
        return status;
    }

    public Response setStatus(Integer status) {
        this.status = status;
        return this;
    }

    /**
     * 通过全局枚举字段直接装配
     *
     * @param status 全局枚举状态码
     * @return 通用返回结果
     */
    public Response setStatus(ResponseStatusEnum status) {
        this.status = status.value();
        this.msg = status.msg();
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public Response setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    public Map<String, Object> getData() {
        return data;
    }

    @Override
    public String toString() {
        return "[" + status + " : " + msg + "] " + data;
    }
}
